package com.dxy.lc.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.dxy.lc.auth.LoginUser;
import com.dxy.lc.base.StatusMessageEnum;
import com.dxy.lc.base.UnifiedException;
import com.dxy.lc.listener.event.UserEditEvent;
import com.dxy.lc.manager.DeptCacheManager;
import com.dxy.lc.mapper.DeptMapper;
import com.dxy.lc.model.entity.Dept;
import com.dxy.lc.model.entity.User;
import com.dxy.lc.manager.UserCacheManager;
import com.dxy.lc.mapper.UserMapper;
import com.dxy.lc.model.bean.UpdPwdDto;
import com.dxy.lc.model.bean.TreeVo;
import com.dxy.lc.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxy.lc.utils.EventUtil;
import com.dxy.lc.utils.LoginUtil;
import com.dxy.lc.utils.MD5Util;
import com.dxy.lc.utils.TreeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author dxy
 * @since 2024-09-23
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private DeptMapper deptMapper;

    @Value("${user.default-password:}")
    private String defaultPassword;

    @Override
    public void add(User entity) {
        String account = entity.getUsername();
        String password = entity.getPassword();
        String deptId = entity.getDeptId();
        Assert.notBlank(deptId, "部门编码不能为空");
        Assert.notBlank(account, "账号不能为空");

        // 验证重名
        Wrapper<User> wrapper = new LambdaQueryWrapper<User>().eq(User::getUsername, account);
        if (baseMapper.selectCount(wrapper) > 0) {
            throw new UnifiedException(500,"用户{}已存在",account);
        }

        if (StrUtil.isBlank(password)){
            password = defaultPassword;
        }
        // 加密密码
        entity.setPassword(MD5Util.getEncryptPassword(password));
        baseMapper.insert(entity);

    }


    @Override
    public void updById(User entity) {
        Assert.notNull(entity.getId(),"id不能为空");
        // 账号和密码不能在这更新
        entity.setPassword(null);
        entity.setUsername(null);
        baseMapper.updateById(entity);
        // 发布用户编辑事件删除缓存
        EventUtil.publishEvent(new UserEditEvent(this, Collections.singletonList(entity.getId())));
    }

    @Override
    @Transactional
    public void delByIds(List<Integer> ids) {
        // 删除用户
        baseMapper.deleteBatchIds(ids);
        // 发布用户编辑事件删除缓存
        EventUtil.publishEvent(new UserEditEvent(this, ids));
    }

    @Override
    public User getDetail(Integer id) {
        User user = UserCacheManager.INSTANCE.getById(id);
        if (user != null) {
            Dept dept = DeptCacheManager.INSTANCE.getById(user.getDeptId());
            user.setDeptName(dept != null ? dept.getName() : "");
        }
        return user;
    }


    @Override
    public void updPwd(UpdPwdDto dto) {
        if (StrUtil.isBlank(dto.getOldPwd()) || StrUtil.isBlank(dto.getNewPwd())) {
            String paramTip = "oldPwd=" + dto.getOldPwd() + ", newPwd=" + dto.getNewPwd();
            throw new UnifiedException(StatusMessageEnum.ILLEGAL_ARGUMENT_ERROR, paramTip);
        }
        LoginUser loginUser = LoginUtil.getLoginUserOrException();
        User dbUser = baseMapper.selectById(Integer.parseInt(loginUser.getUserId()));
        if (dbUser == null) {
            throw new UnifiedException(StatusMessageEnum.ACCOUNT_NOT_EXIST);
        }


        if (!Objects.equals(MD5Util.getEncryptPassword(dto.getOldPwd()), dbUser.getPassword())) {
            throw new UnifiedException(StatusMessageEnum.PWD_ERROR);
        }

        baseMapper.updateById(new User()
                .setId(Integer.parseInt(loginUser.getUserId()))
                .setPassword(MD5Util.getEncryptPassword(dto.getNewPwd())));

    }

    @Override
    public User getLoginUserInfo() {
        LoginUser loginUser = LoginUtil.getLoginUserOrException();
        return getDetail(Integer.parseInt(loginUser.getUserId()));
    }

    @Override
    public List<TreeVo> getContactBook(String kw) {
        LoginUser loginUser = LoginUtil.getLoginUserOrException();
        // 查询所有部门
        List<Dept> depts = deptMapper.selectList(null);
        // 查询所有用户
        List<User> users = baseMapper.selectList(null);
        // 转成treeList
        List<TreeVo> treeVoList = depts.stream().map(Dept::toTreeVo).collect(Collectors.toList());
        // 加入用户节点
        List<User> filteredUsers = users.stream().filter(user -> loginUser.isAdmin() || !user.isAdmin()).collect(Collectors.toList());
        treeVoList.addAll(filteredUsers.stream().map(User::toTreeVo).collect(Collectors.toList()));
        // 构建树
        TreeUtil<TreeVo> treeUtil = new TreeUtil<>(treeVoList);
        if (StrUtil.isEmpty(kw)){
            return treeUtil.buildTree();
        }else{
            Set<String> visibleNodeIds = treeVoList.stream().filter(node -> node.getText().contains(kw)).map(TreeVo::getId).collect(Collectors.toSet());
            treeUtil.buildTree();
            return treeUtil.getFilteredTree(visibleNodeIds);
        }
    }



}
